
const AB2String = (arrayBuffer) => {
  const unit8Arr = new Uint8Array(arrayBuffer)
  const encodedString = String.fromCharCode.apply(null, unit8Arr)
  const decodedString = decodeURIComponent(escape((encodedString)))// 没有这一步中文会乱码
  return decodedString
}

Page({
  data: {
    theme: 'light',
    port: undefined,
    remote_port: undefined,
    startUDP: false,
    mode: 'local',
    address: '10.10.45.95',
    canIUse: true,
    schema: [],
    zh:'',
    title: '',
    result: '',
    options: {},
    apiType: '',
    remark: '',
    webUrl: '',
    apiName: ''
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })

    this.setData({
      apiType: options.zh,
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  },
  handleCreateUDPTap(e) {
    this.UDPSocket = wx.createUDPSocket()
    this.remoteUDPSocket = wx.createUDPSocket()

    this.setData({
      result: this.UDPSocket,
      apiName: e.currentTarget.dataset.apiname
    })
  },
  bindUdpFunc(e) {
    this.port = this.UDPSocket.bind(9000)
    this.remote_port = this.remoteUDPSocket.bind(8088)
    this.setData({
      port: this.port,
      remote_port: this.remote_port,
      startUDP: true,
      result: this.port,
      apiName: e.currentTarget.dataset.apiname
    })
    this.UDPSocket.onMessage((res) => {
      const {remoteInfo} = res
      console.log(res)
      this.setData({
        result:res
      })
      wx.showModal({
        title: `IP:${remoteInfo.address}发来的信息`,
        content: AB2String(res.message),
      })
    })
    this.UDPSocket.onClose(()=>{
      console.log("UDPSocket.onClose")
    })
    this.UDPSocket.onError((res)=>{
      this.setData({
        result:res,
        apiName:'UDPSocket.onError'
      })
    })
    this.UDPSocket.onListening(()=>{
      console.log("UDPSocket.onListening")
      this.UDPSocket.setTTL(64)
    })
  },

  handleCloseUDPTap() {
    this.setData({
      startUDP: false,
      mode: 'local',
    })
    console.log(this.data)
    this.UDPSocket.close()
    this.remoteUDPSocket.close()
  },
  connect(e) {
    this.UDPSocket.connect({
      address: this.data.address || '10.10.45.95', // 可以是任意 ip 和域名
      port: this.remote_port,
    })
  },

  handleSendRemoteMessage() {
    this.UDPSocket.send({
      address: this.data.address || '10.10.45.95', // 可以是任意 ip 和域名
      port: this.remote_port,
      message: `port[${this.port}] 向 remote-port[${this.remote_port}] 发送信息: Hello Wechat!`,
    })
  },
  write(){
    this.UDPSocket.write({
      address: this.data.address || '10.10.45.95', // 可以是任意 ip 和域名
      port: this.remote_port,
      message: `port[${this.port}] 向 remote-port[${this.remote_port}] 发送信息: Hello Wechat!`,
    })
  },
  changeMode() {
    this.setData({
      mode: 'remote',
    })
  },
  handleInputChange(e) {
    this.setData({
      address: e.detail.value,
    })
  }
})
